﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Single.AppCore;
using Single.Core.Service;
using Single.Sys.Entity;
using Single.WebApp.Components;

namespace Single.WebApp.Areas.Work.Controllers
{
    [Area("Work")]
    public class HomeController : WorkController
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Welcome()
        {
            return View();
        }

        public IActionResult Dialog()
        {
            return View();
        }

        [AllowAnonymous]
        public async Task<IActionResult> Authorize()
        {
            if (IsAuthenticated)
            {
                await HttpContext.SignOutAsync(AuthScheme);
            }

            return View();
        }

        [AllowAnonymous]
        public async Task<string> Login(string username, string password)
        {
            var result = ServiceSysProps.SysUser.SignIn(username, password);

            if (result.Success)
            {
                var user = result.Data as SysUser;

                await HttpContext.SignInAsync(AuthScheme, user.Id, user.Name, user.Username, user.Avatar, user.PasswordTime, user.IsSuper);
            }

            return result.Serialize();
        }

        [AllowAnonymous]
        public async Task<IActionResult> Logout()
        {
            if (IsAuthenticated)
            {
                await HttpContext.SignOutAsync(AuthScheme);
            }

            return Redirect("/work/home/authorize");
        }

        public string GetMenu()
        {
            var menus = ServiceSysProps.SysMenu.GetByUserId(UserId, IsSuper);

            return ServiceResult.SerializeData(menus);
        }
    }
}